//用户数据库方法
package com.cuijian.demo.model;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.List;

public class User extends Model<User> {

    public static final User dao = new User();

    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        return dao.findFirst("SELECT * FROM user WHERE username = ? AND status = 1", username);
    }

    /**
     * 根据邮箱查找用户
     */
    public User findByEmail(String email) {
        return dao.findFirst("SELECT * FROM user WHERE email = ? AND status = 1", email);
    }

    /**
     * 分页查询用户列表
     */
    public Page<User> paginate(int pageNumber, int pageSize) {
        return dao.paginate(pageNumber, pageSize, "SELECT *", "FROM user WHERE status = 1 ORDER BY create_time DESC");
    }

    /**
     * 检查用户名是否存在
     */
    public boolean isUsernameExists(String username) {
        return dao.findFirst("SELECT id FROM user WHERE username = ?", username) != null;
    }

    /**
     * 检查邮箱是否存在
     */
    public boolean isEmailExists(String email) {
        return dao.findFirst("SELECT id FROM user WHERE email = ?", email) != null;
    }

    /**
     * 更新最后登录信息
     */
    public boolean updateLoginInfo(Long userId, String loginIp) {
        return dao.findById(userId)
                .set("last_login_time", new Date())
                .set("last_login_ip", loginIp)
                .update();
    }

    // Getter方法
    public Long getId() {
        return getLong("id");
    }

    public String getUsername() {
        return getStr("username");
    }

    public String getPassword() {
        return getStr("password");
    }

    public String getEmail() {
        return getStr("email");
    }

    public String getPhone() {
        return getStr("phone");
    }

    public String getRealName() {
        return getStr("real_name");
    }

    public String getAvatar() {
        return getStr("avatar");
    }

    public Integer getStatus() {
        return getInt("status");
    }

    public Date getCreateTime() {
        return getDate("create_time");
    }

    public Date getUpdateTime() {
        return getDate("update_time");
    }
}